package com.ssy.lingxi.pay.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Description:
 * @Author: HuangJieZhou
 * @Date: 2021/12/20 20:05
 * @Version: 2.0.0
 **/
public class MD5Util {

    public static String md5Str(String str) {
        if (str == null) return "";
        return md5Str(str, 0);
    }

    /**
     * 计算消息摘要。
     *
     * @param str    计算摘要的数据。
     * @param offset 数据偏移地址。
     * @return 摘要结果。(16字节)
     */
    public static String md5Str(String str, int offset) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] b = str.getBytes(StandardCharsets.UTF_8);
            md5.update(b, offset, b.length);
            return byteArrayToHexString(md5.digest());
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * @param b byte[]
     * @return String
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder result = new StringBuilder();
        for (byte value : b) {
            result.append(byteToHexString(value));
        }
        return result.toString();
    }

    private static final String[] hexDigits =
            {
                    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b",
                    "c", "d", "e", "f"};

    /**
     * 将字节转换为对应的16进制明文
     *
     * @param b byte
     * @return String
     */
    public static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static void main(String[] args) {
        String str = "MERCHANTID=105003153113691&POSID=058174332&BRANCHID=371000000&ORDERID=202112202200001&PAYMENT=0.1&CURCODE=01&TXCODE=690401&REMARK1=&REMARK2=";
//        String str = "MERCHANTID=105003153113691&POSID=058174333&BRANCHID=371000000&ORDERID=593019478185511&PAYMENT=0.1&CURCODE=01&TXCODE=690401&REMARK1=&REMARK2=&TIMEOUT=";
//        System.out.println(byteToHexString((byte) -99));

        String ened = MD5Util.md5Str(str);
        System.out.println(ened.length());
        System.out.println(ened);
    }
}
